﻿using System;
using System.Linq;
using System.Web.Mvc;
using System.Web.UI;
using ccgstore.WebApp.Models;
using ccgstore.WebApp.ViewModels;
using WebMatrix.WebData;

namespace ccgstore.WebApp.Controllers
{
    public class ForumController : ControllerBase
    {

        CcgStoreRepository _ccgStoreRepository = new CcgStoreRepository();

        //
        // GET: /Forum/

        public ActionResult ForumCategories()
        {
            var vm = new ForumVm();
            vm.ForumCategories = Db.ForumCategories.ToList();
            vm.GeneralThreads = Db.Threads.Where(t => t.ForumCategoryId == null).ToList();

            return View(vm);
        }

        public ActionResult NewThread()
        {
            var vm = new NewThreadVm
            {
                ForumCategories = Db.ForumCategories.ToList()
            };

            return View(vm);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        [Authorize]
        public ActionResult NewThread(NewThreadVm threadVm)
        { 
            if (ModelState.IsValid)
            {
                var vmThread = threadVm.Thread;
                var vmPost = threadVm.Post;
                var user = Db.Users.First(u => u.Name == User.Identity.Name);

                var thread = Db.Threads.Create();
                thread.CreateDt = DateTimeOffset.Now;
                thread.ForumCategory = vmThread.ForumCategory;
                thread.Subject = vmThread.Subject;
                thread.User = user;
                Db.Threads.Add(thread);

                Db.SaveChanges();

                var post = Db.Posts.Create();
                post.Content = vmPost.Content.Replace(Environment.NewLine, "<br />");
                post.CreateDt = DateTimeOffset.Now;
                post.Thread = thread;
                post.User = user;
                Db.Posts.Add(post);

                Db.SaveChanges();

                return RedirectToAction("ViewThread", "Forum", new { index = thread.ThreadId });
            }

            threadVm.ForumCategories = Db.ForumCategories.ToList();

            return View(threadVm);
        }

        public ActionResult ViewThread(int index)
        {
            var thread = Db.Threads.Single(t => t.ThreadId == index);

            var threadVm = new ViewThreadVm(thread);
           
            return View(threadVm);
        }

        public ActionResult IndexCategory(ForumCategory category)
        {
            return View();
        }
    }
}
